﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;
using System;
using Topshelf;

namespace QuartzJob.Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            //var host = CreateHostBuilder(args).Build();

            //HostFactory.Run(x =>
            //{
            //    x.Service<IHost>(s =>
            //    {
            //        s.ConstructUsing(n => host);
            //        s.WhenStarted(tc => tc.StartAsync());
            //        s.WhenStopped(tc => tc.StopAsync().Wait());
            //    });
            //    x.RunAsLocalSystem();

            //    x.SetDisplayName("Quartz.Sample.JobService");
            //    x.SetServiceName("Quartz.Sample.JobService");
            //});


            var host = CreateHostBuilder(args).Build();
            host.Run();
        }


        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
                .ConfigureLogging(loggingBuilder =>
                {
                    loggingBuilder.AddConsole();
                    loggingBuilder.SetMinimumLevel(LogLevel.Information);
                })
                .ConfigureServices((context, services) =>
                {
                    services.AddTransient<SampleJob>()
                        .AddTransient<DisposedSampleJob>()
                        .AddTransient<IDisposableService, DisposableService>()
                        .AddSingleton<IJobFactory, MyJobFactory>()
                        .AddSingleton<IScheduler>(sp =>
                        {
                            var scheduler = StdSchedulerFactory.GetDefaultScheduler().ConfigureAwait(false).GetAwaiter().GetResult();
                            scheduler.JobFactory = sp.GetRequiredService<IJobFactory>();
                            return scheduler;
                        })
                        .AddHostedService<QuartzJobHostedService>();
                })
                //if install by topshelf,don't need this
                .UseWindowsService();

    }
}
